package org.kev.transit;

import java.util.*;


import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import org.kev.transit.data.Route;
import org.kev.transit.util.TransitConst;
import org.kev.transit.util.TransitUtil;
import org.kev.transit.worker.DataWorker;


/**
 * Route/ Line screen.   
 * The data displayed is based on a Web service(JSON) call that is then cached in
 * the local DB.  Some day it will also expire cached data in the DB.  All DB updates 
 * occur in a background thread.
 * @author kevin
 *
 */

public class RouteActivity extends DataActivity {
	public static final int BACK_ID = FIRST_MENU+1;
	public static final int NEXT_ID = FIRST_MENU + 2;
	public static final int SETTINGS_ID = FIRST_MENU + 3;
	public static final String TAG = "Transit";
	private ListView mRouteView = null;
	private  ArrayAdapter <Route> arrayAdapter=null;
	/** setup worker thread object */
	private static final DataWorker mWorker = new DataWorker();

    // Need handler for call backs to the UI thread
    private final Handler mHandler = new Handler();
   
    
	public RouteActivity() {

	}

/**
 *  Called when fist started
 *  @param icicle
 */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		try {
			
			// Inflate our UI from its XML layout description.
	        requestWindowFeature(Window.FEATURE_PROGRESS);
			
			Log.d(TAG,"INFLAGE XML!!!");
			setContentView(R.layout.route);
	        setProgressBarVisibility(true);
	        setProgressBarIndeterminate(true);
	        final Intent intent = getIntent();	      
	        if(intent.getData()!=null){
	        	intent.setData(Route.CONTENT_URI);
	        }
			
	        mRouteView =     (ListView) findViewById(R.id.routeList);
	        mRouteView.setOnItemSelectedListener(mRouteListener );
	        mRouteView.setOnItemClickListener(mItemListener);
;
			
			// Hook up button presses to the appropriate event handler.
			//((Button) findViewById(R.id.back)).setOnClickListener(mBackListener);
			//((Button) findViewById(R.id.next)).setOnClickListener(mNextListener);
		

		} catch (Exception e) {
			Log.e(TransitConst.TAG,"UKNOWN Error in "+this,e);
			AlertDialog.show(this,"StackTrace",R.drawable.icon, e.getMessage(), "Ok", false);
		}
	}
	
	/**
	 * set the currently select rout item based on pref if it exist
	 * @param routeSpin
	 */
	private void setCurrentRoute(ListView routeView) {
	       SharedPreferences settings = getSharedPreferences(TransitConst.PREFS_NAME, 0);
		   String current = settings.getString(TransitConst.ROUTE_PREF,"");
		   Log.d(TAG,"current pref="+current);
		   ListAdapter adapt= routeView.getAdapter();
		   int count =routeView.getCount();
		   for (int i=0;i<count;i++){
			   String s =adapt.getItem(i).toString();
			   if (s.equals(current) && s!=null){
				   Log.d(TransitConst.TAG,"found slection"+s);
				   routeView.setSelection(i);
				   return;
			   }
		   }
	}

	
	/**
	 * Called when the activity is about to start interacting with the user.
	 */
	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TransitConst.TAG,".onResume restore Prefs !");
		 setProgressBarVisibility(true);
		mWorker.init(this,mHandler,mUpdateResults);
		Thread t = new Thread(mWorker);
		t.setDaemon(true);
		t.start();		
		
		//call update spinners

	
	}
/**
 * 
 * I am being paused save all prefs
 */
	@Override
	protected void onPause() {
		super.onPause();
		
		Log.d(TransitConst.TAG,"onPAUSE Save Prefs!");
		Log.d(TransitConst.TAG,TransitConf.toXML() );
		TransitUtil.savePref(this,TransitConst.ROUTE_PREF,TransitConf.currentRoute );
		}
	
    @Override
    protected void onFreeze(Bundle outState) {
    	super.onFreeze(outState);
    	TransitUtil.savePref(this,TransitConst.ROUTE_PREF,TransitConf.currentRoute );
        // Remember state
      //  outState.putBundle("transit-view", mLunarView.saveState());
    }
	/**


	/**
	 * Called when your activity's options menu needs to be created.
	 * @param menu
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		// We are going to create two menus. Note that we assign them
		// unique integer IDs, labels from our string resources, and
		// given them shortcuts.


		return true;
	}

	/**
	 * Called right before your activity's option menu is displayed.
	 *  @param menu
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

		// Before showing the menu, we need to decide whether the clear
		// item is enabled depending on whether there is text to clear.
		// menu.setItemShown(CLEAR_ID, mEditor.getText().length() > 0);

		return true;
	}

	/**
	 * Called when a menu item is selected.
	 *  @param item
	 *  
	 */  
	@Override
	public boolean onOptionsItemSelected(Menu.Item item) {
		switch (item.getId()) {
		case NEXT_ID:
			nextScreen();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}
	/**
	 * Jump to next Screen (StopActivity)
	 */
	public void nextScreen(){

		this.startActivity(TransitConst.DIRECTION_INTENT );
	}
	
	/**
	 * set route view this needs to be moved to a worker thread
	 */
	public void setData(){
		Cursor cursor=null;
		try{
		
				Uri curi  = Uri.parse("content://transit/route");
				String routeTypeId = TransitConf.currentRouteTypeId;
					ArrayList <Route> list = Route.getData(this, routeTypeId);

				arrayAdapter =new  ArrayAdapter <Route> (this,android.R.layout.simple_list_item_1,list);
				//mRouteView.setAdapter(mRouteAdapter);
		
		}catch(Exception e){
			Log.e(TAG,"setRoute()",e);
		}finally{
			if (cursor!=null)
				cursor.close();
		}
	}

	
	/**
	 *   save selected item in a TransitConf object
	 */
	private void routeSelected(){
		Log.d(TAG,"route selected");
		
//		mRouteSpin.getSelectedItem();
		if( mRouteView.getSelectedItem()!=null){
			Route temp =(Route) mRouteView.getSelectedItem();
			TransitConf.currentRoute=temp.title;
			TransitConf.currentRouteId=temp.id;
		
		}
		
	}

	//****************INNER CLASSES***********************************
    // Create runnable for posting
  
    /**
     *  Create runnable for posting ui updates
     */
   Runnable mUpdateResults = new Runnable() {

    	public void run() {
    		Log.d(TAG,"set mUpdateResults.run()=");
        	mRouteView.setAdapter(arrayAdapter);
        	setCurrentRoute(mRouteView);
        	 setProgressBarVisibility(false);      	}
    };
	/**
	 * A call-back for click on a selected item
	 */
    OnItemClickListener mItemListener = new OnItemClickListener() {

		public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
			nextScreen();
			
		}
	};
	/**
	 * A call-back for when select a route type.
	 */
	OnItemSelectedListener mRouteListener = new OnItemSelectedListener() {
		public void onItemSelected(AdapterView parent, View v, int position, long id){
			routeSelected();
			
		}
		public void onNothingSelected(AdapterView parent){}
	};
	/**
	 * A call-back for when the user presses the Next button.
	 */
/*	OnClickListener mNextListener = new OnClickListener() {
		public void onClick(View v) {
			nextScreen();
		}
	};
	*/
	/**
	 * A call-back for when the user presses the back button.
	 */
	/*OnClickListener mBackListener = new OnClickListener() {
		public void onClick(View v) {
			finish();
		}
	};*/

}